package com.alan.mr.trackuser;

import org.apache.hadoop.io.Text;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Alan on 2017/10/22.
 */
public class TableLine {

    private String imsi;
    private String position;
    private String time;
    private String timeFlag;
    private Date day;

    private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public void set(String line,boolean source,String date,String[] timepoint) throws LineException{
        String[] lineSplit = line.split("\t");
        if(source){
            this.imsi = lineSplit[0];
            this.position = lineSplit[3];
            this.time = lineSplit[4];
        } else{
            this.imsi = lineSplit[0];
            this.position = lineSplit[2];
            this.time = lineSplit[3];
        }
        if(!this.time.startsWith(date)){//检查时间是否与输入的相同
            throw new LineException("",-1);//与输入时间不同，flag是-1
        }
        try {
            this.day = this.formatter.parse(this.time);
        } catch (ParseException e) {
            throw new LineException("",0);//格式不对，flag是0
        }
        //下面是判断时间是否在指定的时间段里面
        int i=0,n=timepoint.length;//数组中的元素个数
        int hour = Integer.valueOf(this.time.split(" ")[1].split(":")[0]);//yyyy-MM-dd HH:mm:ss 提取HH
        while(i<n && Integer.valueOf(timepoint[i])< hour)
            i++;
        if(i<n) {
            if(i==0)
                this.timeFlag=("00-" + timepoint[i]);//判断是否在时间段之前，然后输出时间段
            else
                this.timeFlag = ( timepoint[i-1]+"-"+timepoint[i]);
        }else{
            throw new LineException("",-1);//不是在指定的时间段里面
        }
    }

    public Text outKey(){
        return new Text(this.imsi+"|"+this.timeFlag);
    }

    public Text outValue(){
        long t = (day.getTime()/1000L);  //用一个UNIX的时间，getTime本身就是返回一个unix的时间
        return new Text(this.position+"|"+String.valueOf(t));
    }
}
